﻿// Maintain array of dates
var dates = new Array();
function addDate(date) { if ($.inArray(date, dates) < 0) dates.push(date); }
function removeDate(index) { dates.splice(index, 1); }

// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
    var index = $.inArray(date, dates);
    if (index >= 0)
        removeDate(index);
    else
        addDate(date);
}

// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
    var ret = new String(number);
    if (ret.length == 1)
        ret = "0" + ret;
    return ret;
}

function insertZeroForDayOrMonth(value) {
    if (value < 10)
        value = "0" + value;
}
// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

$().ready(function () {
    $('.button').button();
    var employeesGrid = setUpEmployeesGrid($('#employeesGrid'));
});

// Sets up the sample grid
function setUpEmployeesGrid($gridSelector) {
    // First, define the grid's columns

    function nameFormatter(row, cell, value, columnDef, dataContext) {
        return dataContext.FirstName + " " + dataContext.MiddleName + " " + dataContext.LastName;
    }
    var columns = [
        { id: "Name", name: "Name", field: "", width: 200, sortable: true, formatter: nameFormatter },
        { id: "PhoneNumber", name: "Phone Number", field: "PhoneNumber", width: 200, sortable: true },
        { id: "EmailAddress", name: "Email Address", field: "EmailAddress", width: 300, sortable: true },
        { id: "buttons", name: "", field: "", width: 290, sortable: false, formatter: CellButtonFormatter, buttons: ["Edit", "Availability", "Delete"] }
    ];


    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));
    grid.updateHeaderRow();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $('.slick-cell-button').button();
    });
    block({ element: $gridSelector, text: 'Loading' });
    $.getJSON('/EmployeeManagement/ListEmployees', function (response) {
        if (response.Result)
            grid.dataView.setItems(response.Data);
        else {
            alert(response.Data);
        }
    });
    unblock({ element: $gridSelector });
    setUpAddEmployeeDialog();
    setUpDeleteEmployeeDialog();
    setUpEditEmployeeDialog();
    setUpAvailabilityDialog();
    $('.datepicker').datepicker({
        changeMonth: true,
        changeYear: true

    });
    grid.onCellChange.subscribe(function (e, args) {
//        block({ element: $gridSelector, text: 'Saving' });

//        $.put(jQuery.validator.format('/schedulemanagement/update', args.item.Id, clientsGrid.getActiveRowData().ResourceId),
//                { accessLevel: args.item.AccessLevel },
//                function () {
//                    grid.dataView.updateItem(args.item.Id, args.item);
//                })
//                .error(function (result) { alert('Unable to update client access:' + result); })
//                .complete(function () { unblock({ element: $grid }); });
    });

    // Return the grid object so we can store it in a variable
    return grid;

    function setUpAddEmployeeDialog() {
        var $dialog = $('#addEmployeeDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 300,
            height: 600,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        // Post to the server
                        $.post('/EmployeeManagement/CreateEmployee',
                        // Set up the data to transfer
                           extractFormData($('#addEmployeeForm')),
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.addItem(response.Data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#addEmployeeForm'));

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#addEmployeeForm'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#addEmployeeButton').click(function () {
            $dialog.dialog('open');
        });
    }
    function setUpAvailabilityDialog() {
        var $selectedTagInput;
        var $dialog = $('#availabilityDialog');
        function extractAvailableTimes() {
            var data = [];
            $('#availabilityForm > input').each(function () {
                var times = $(this).val().split(',');
                for (var i = 0; i < times.length; i++) {
                    if (times[i] !== undefined && times[i] != "") {
                        var range = times[i].split('-');
                        data.push({ Day: this.id, From: convertTimeToInteger(range[0]), To: convertTimeToInteger(range[1]) });
                    }
                }
            });
            return data;
        }
        function convertTimeToInteger(time) {
            //            debugger;
            var offset = 0;
            if (time.indexOf('PM') != -1)
                offset = 12;
            if (time.indexOf(' ') != -1)
                time = time.substring(0, time.indexOf(' '));

            var units = time.split(':');
            units[1] = parseInt(units[1]) + (parseInt(units[0]) + offset) * 60;

            return units[1];
        }
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            height: 500,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        // Post to the server
                        $.ajax({
                            type: 'POST',
                            url: '/EmployeeManagement/UpdateEmployeeAvailability',
                            dataType: 'json',
                            traditional: false,
                            data: {
                                employeeId: grid.getDataItem(grid.getActiveCell().row).Id,
                                availableTimes: JSON.stringify(extractAvailableTimes())
                            },
                            success: function (response) {
                                if (response.Result) {
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#availabilityForm'));

                                // Close the dialog
                                $this.dialog('close');
                            },
                            error: function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            }
                        });

                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#availabilityForm'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#availabilityForm input').each(function () {
            $(this).tagsInput({ interactive: true });
        });
        $('#timePicker').dialog({
            modal: true,
            autoOpen: false,
            width: 150,
            resizable: false,
            buttons: {
                OK: function () {
                    //                    debugger;
                    $selectedTagInput.addTag($('#timePicker input[name="From"]').val() + "-" + $('#timePicker input[name="To"]').val());
                    // Clear the fields
                    clearForm($('#timePicker form'));

                    // Close the dialog box
                    $(this).dialog('close');
                },
                Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#timePicker form'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
            }
        });
        var $from = $('#timePicker input[name="From"]');
        var $to = $('#timePicker input[name="To"]');
        $('#timePicker input').timepicker({
            showCloseButton: true,
            minutes: {
                starts: 0,                // First displayed minute
                ends: 59,                 // Last displayed minute
                interval: 15                // Interval of displayed minutes
            },
            showPeriod: true,
            onHourShow: OnHourShowCallback,
            onMinuteShow: OnMinuteShowCallback,
            defaultTime: '12:00'
        });
        function OnHourShowCallback(hour) {
            if (this.name == "From" && $to.val() != '') {
                if (hour >= $to.timepicker('getHour')) {
                    return false; // not valid
                }
            }
            else if (this.name == "To" && $from.val() != '') {
                if (hour <= $from.timepicker('getHour')) {
                    return false; // not valid
                }

            }
            return true;
        }
        function OnMinuteShowCallback(hour, minute) {
            if ((hour == 20) && (minute >= 30)) { return false; } // not valid
            if ((hour == 6) && (minute < 30)) { return false; }   // not valid
            return true;  // valid
        }
        $('.tagsinput button').click(function (event) {
            event.stopPropagation();
            $selectedTagInput = $('#' + this.id.replace(/\_tag/, ""));
            //            debugger;
            $('#timePicker').dialog('open');
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Availability', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);
            for (var day in row.AvailableTimes) {
                $('#' + day).importTags(row.AvailableTimes[day]);
            }
            //            $('#availabilityForm').find('input, select').each(function () {
            //                $(this).val(row[this.name]);
            //            });
            //$('#employeeName').text(row.FirstName + " " + row.MiddleName + " " + row.LastName);
            $dialog.dialog('open');
        });
    }
    function setUpTimePicker() {
        
        var $selectedTagInput;
        var $dialog = $('#availabilityDialog');
        function extractAvailableTimes() {
            var data = [];
            $('#availabilityForm > input').each(function () {
                var times = $(this).val().split(',');
                for (var i = 0; i < times.length; i++) {
                    if (times[i] !== undefined && times[i] != "") {
                        var range = times[i].split('-');
                        data.push({ Day: this.id, From: convertTimeToInteger(range[0]), To: convertTimeToInteger(range[1]) });
                    }
                }
            });
            return data;
        }
        function convertTimeToInteger(time) {
            //            debugger;
            var offset = 0;
            if (time.indexOf('PM') != -1)
                offset = 12;
            if (time.indexOf(' ') != -1)
                time = time.substring(0, time.indexOf(' '));

            var units = time.split(':');
            units[1] = parseInt(units[1]) + (parseInt(units[0]) + offset) * 60;

            return units[1];
        }
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            height: 500,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        // Post to the server
                        $.ajax({
                            type: 'POST',
                            url: '/EmployeeManagement/UpdateEmployeeAvailability',
                            dataType: 'json',
                            traditional: false,
                            data: {
                                employeeId: grid.getDataItem(grid.getActiveCell().row).Id,
                                availableTimes: JSON.stringify(extractAvailableTimes())
                            },
                            success: function (response) {
                                if (response.Result) {
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#availabilityForm'));

                                // Close the dialog
                                $this.dialog('close');
                            },
                            error: function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            }
                        });

                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#availabilityForm'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#availabilityForm input').each(function () {
            $(this).tagsInput({ interactive: true });
        });
        $('#timePicker').dialog({
            modal: true,
            autoOpen: false,
            width: 150,
            resizable: false,
            buttons: {
                OK: function () {
                    //                    debugger;
                    $selectedTagInput.addTag($('#timePicker input[name="From"]').val() + "-" + $('#timePicker input[name="To"]').val());
                    // Clear the fields
                    clearForm($('#timePicker form'));

                    // Close the dialog box
                    $(this).dialog('close');
                },
                Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#timePicker form'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
            }
        });
        var $from = $('#timePicker input[name="From"]');
        var $to = $('#timePicker input[name="To"]');
        $('#timePicker input').timepicker({
            showCloseButton: true,
            minutes: {
                starts: 0,                // First displayed minute
                ends: 59,                 // Last displayed minute
                interval: 15                // Interval of displayed minutes
            },
            showPeriod: true,
            onHourShow: OnHourShowCallback,
            onMinuteShow: OnMinuteShowCallback,
            defaultTime: '12:00'
        });
        function OnHourShowCallback(hour) {
            if (this.name == "From" && $to.val() != '') {
                if (hour >= $to.timepicker('getHour')) {
                    return false; // not valid
                }
            }
            else if (this.name == "To" && $from.val() != '') {
                if (hour <= $from.timepicker('getHour')) {
                    return false; // not valid
                }

            }
            return true;
        }
        function OnMinuteShowCallback(hour, minute) {
            if ((hour == 20) && (minute >= 30)) { return false; } // not valid
            if ((hour == 6) && (minute < 30)) { return false; }   // not valid
            return true;  // valid
        }
        $('.tagsinput button').click(function (event) {
            event.stopPropagation();
            $selectedTagInput = $('#' + this.id.replace(/\_tag/, ""));
            //            debugger;
            $('#timePicker').dialog('open');
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Availability', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);
            for (var day in row.AvailableTimes) {
                $('#' + day).importTags(row.AvailableTimes[day]);
            }
            //            $('#availabilityForm').find('input, select').each(function () {
            //                $(this).val(row[this.name]);
            //            });
            //$('#employeeName').text(row.FirstName + " " + row.MiddleName + " " + row.LastName);
            $dialog.dialog('open');
        });
    }
    function setUpEditEmployeeDialog() {
        var $dialog = $('#editEmployeeDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            height: 700,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        var data = extractFormData($('#editEmployeeForm'));
                        // Post to the server
                        $.post('/EmployeeManagement/UpdateEmployee',
                        // Set up the data to transfer
                           data,
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    grid.dataView.updateItem(data.Id, data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#editEmployeeForm'));

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#editEmployeeForm'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Edit', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);

            $('#editEmployeeForm').find('input, select').each(function () {
                $(this).val(row[this.name]);
            });
            //$('#employeeName').text(row.FirstName + " " + row.MiddleName + " " + row.LastName);
            $dialog.dialog('open');
        });
    }
    function setUpDeleteEmployeeDialog() {
        var $dialog = $('#deleteEmployeeDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var id = grid.getDataItem(grid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/EmployeeManagement/DeleteEmployee',
                        // Set up the data to transfer
                            {id: id },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.deleteItem(id);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Delete', function () {

            var row = grid.getDataItem(grid.getActiveCell().row);
            //            debugger;
            $('#employeeName').text(row.FirstName + " " + row.MiddleName + " " + row.LastName);
            $dialog.dialog('open');
        });
    }
}